import logging
import inspect
import sys

import os
import azure.functions as func
import json

logger = logging.getLogger(__name__)

CURRENTDIR = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
PARENTDIR = os.path.dirname(CURRENTDIR)
sys.path.insert(0, CURRENTDIR)
sys.path.insert(0, PARENTDIR)

from mobile.bmp212.sensordata import sensor_data


def str2bool(v):
  return v.lower() in ("yes", "true", "t", "1")

def main(req: func.HttpRequest) -> func.HttpResponse:
    try:
        body = req.get_json()
        if "motion" in body.keys():
            motion = body.get("motion")
            if not isinstance(motion, bool):
                motion = str2bool(motion)
        else:
            motion = False
        if "orientation" in body.keys():
            orientation = body.get("orientation")
            if not isinstance(orientation, bool):
                orientation = str2bool(orientation)
        else:
            orientation = False
        package = body.get("package")
        version = body.get("version")
        if version == "2.1.2":
            t = sensor_data(orientation=orientation, motion=motion, package=package)
            return func.HttpResponse(body=json.dumps({"sensordata": t.generate_sd(), "version": "2.1.2"}),
                             headers={"Content-Type": "application/json"})
        else:
            return func.HttpResponse(body=json.dumps({"error": "version unavailable"}), status_code=400,
                                     headers={"Content-Type": "application/json"})
    except (KeyError, ValueError):
        logger.error(json.dumps(req.get_json()), exc_info=True)
        return func.HttpResponse(body=json.dumps({"error":"request error - missing fields"}), status_code=400, headers={"Content-Type": "application/json"})
    except Exception as e:
        logger.error("error: {}".format(str(e)), exc_info=True)
        # return func.HttpResponse(body=json.dumps({"error":e.message}, status_code=400, headers={"Content-Type": "application/json"}))
        return func.HttpResponse(body=json.dumps({"error":"request error {}".format(str(e.args))}), status_code=400, headers={"Content-Type": "application/json"})

